# -*- coding: utf-8 -*-

import pandas as pd

import indicator.ta_series as stai
from config.system_conf import bq_log
# from strategy.template import IStrategy
from strategy.istrategy import IStrategy


class StraDMA(IStrategy):
    pma1 = 5
    pma2 = 25
    data_len = 50
    ma1 = None
    ma2 = None

    def __init__(self, parent=None, stra_ee=None, period=0, params=None, setting=None, data_ee=None):
        super(StraDMA, self).__init__(parent, stra_ee, period, params, setting, data_ee)

    def on_tick(self, tick):
        self.tick = tick
        price = tick.LastPrice
        ma1 = self.ma1.iloc[-1] * (self.pma1 - 1) / self.pma1 + price / self.pma1
        ma2 = self.ma2.iloc[-1] * (self.pma2 - 1) / self.pma2 + price / self.pma2
        # print(ma1,ma2)
        self.ma1 = self.ma1.append(pd.Series([ma1], index=[tick.DateTime]))
        self.ma2 = self.ma2.append(pd.Series([ma2], index=[tick.DateTime]))
        crs1 = stai.single_cross(self.ma1[-3:], self.ma2[-3:])
        crs2 = stai.single_cross(self.ma2[-3:], self.ma1[-3:])
        if crs1:
            self.cover(tick.LastPrice, dt=tick.DateTime)
            self.buy(tick.LastPrice, dt=tick.DateTime)
        elif crs2:
            self.sell(tick.LastPrice, dt=tick.DateTime)
            self.short(tick.LastPrice, dt=tick.DateTime)
        bs = 1 if crs1 else -1 if crs2 else 0
        if bs != 0:
            # print(f'dma:ma1[-5:]={self.ma1.tail(5)}')
            # print(self.ma2.tail(5))
            self.to_signal(bs=bs)

    def on_ticks(self, ticks, pma1=None, pma2=None):
        super().on_ticks(ticks)
        if not pma1:
            pma1 = self.pma1
        else:
            self.pma1 = pma1
        if not pma2:
            pma2 = self.pma2
        else:
            self.pma2 = pma2

        ma1 = stai.ma(ticks.LastPrice, pma1)
        ma2 = stai.ma(ticks.LastPrice, pma2)
        # buy-sell flag: buy=(bs==1),sell=(bs==-1)
        bs = stai.cross(ma1, ma2)
        bssc = bs[bs != 0]

        # print(f'{pma1!r}:{pma2!r}:len={len(bssc)}')
        # print(self.__dict__)
        # print(bssc)
        self.to_signals(bssc)
        self.ma1 = ma1
        self.ma2 = ma2

    def on_bar(self, bar):
        super().on_bar(bar)
        price = bar.close
        ma1 = self.ma1.iloc[-1] / self.pma1 + price * (self.pma1 - 1) / self.pma1
        ma2 = self.ma2.iloc[-1] * (self.pma2 - 1) / self.pma2 + price / self.pma2
        self.ma1 = self.ma1.append(pd.Series([ma1], index=[bar.datetime]))
        self.ma2 = self.ma2.append(pd.Series([ma2], index=[bar.datetime]))
        crs1 = stai.single_cross(self.ma1[-3:], self.ma2[-3:])
        crs2 = stai.single_cross(self.ma2[-3:], self.ma1[-3:])
        tick = self.bars.tick

        if crs1:
            self.cover(tick.LastPrice, dt=tick.DateTime)
            self.buy(tick.LastPrice, dt=tick.DateTime)
        elif crs2:
            self.sell(tick.LastPrice, dt=tick.DateTime)
            self.short(tick.LastPrice, dt=tick.DateTime)
        bs = 1 if crs1 else -1 if crs2 else 0

        if bs != 0:
            # print(f'dma:ma1[-5:]={self.ma1.tail(5)}')
            # print(self.ma2.tail(5))
            self.to_signal(bs=bs)

    def on_bars(self, bars, **params):
        super().on_bars(bars)
        # print(self.pma1,self.pma2)
        self.ma1 = stai.ema(bars.c, self.pma1)
        self.ma2 = stai.ema(bars.c, self.pma2)
        bssc = stai.cross(self.ma1, self.ma2)
        self.to_signals(bssc)


def on_ticks(ticks, pma1=None, pma2=None):
    ma1 = stai.ema(ticks['LastPrice'], pma1)
    ma2 = stai.ema(ticks['LastPrice'], pma2)
    # buy-sell flag: buy=(bs==1),sell=(bs==-1)
    bs = stai.cross(ma1, ma2)
    return bs


if __name__ == '__main__':
    import datetime
    import pandas as pd
    from data.get_data_hf_zmq import get_frame_bar
    from utils.function import create_class_instance
    import instrument.manager as im
    from indicator.df_bar import Bars

    inst = im.StraInstr('rb2001')
    sc = 'StraDMA'
    sm = 'strategy.strategy_double_ma'
    stt = {'pma1': 60, 'pma2': 300, 'period': 60}
    dma = create_class_instance(sm, sc, setting=stt)
    print(dma.pma1, dma.id)
    ed = datetime.datetime.now().strftime('%Y%m%d')
    sd = (datetime.datetime.now() - datetime.timedelta(10)).strftime('%Y%m%d')
    sl = ['SHFE.rb2001']
    bq_log.info('start to get ticks')
    br = get_frame_bar(symbol='rb2001', sd=sd, ed=ed)
    brs = Bars(parent=inst, data=br)

    print(brs.__dict__)

    inst.add_bars(bars=brs)
